﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;


public partial class Manager_ImportHD_ImportHD : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["AdminUserID"] == null)
        {
            Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
            return;
        }
    }
    private bool CheckFileUpload(string sFileName)
    {
        bool b = false;//not ok
        string FileTypeExcept = ConfigurationManager.AppSettings["FileExcept"];
        string sFileType = GetFileType(sFileName);

        string[] arr = FileTypeExcept.Split(';');
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].ToUpper().Trim() == sFileType.ToUpper().Trim())
            {
                b = true;
                break;
            }
        }

        return b;
    }
    private string GetFileType(string sFileName)
    {
        string[] arr = sFileName.Split('.');
        if (arr.Length > 1)
        {
            return arr[arr.Length - 1];
        }
        return "";
    }
    private bool CheckDecimal(string value)
    {
        bool b = true;//is a number
        try
        {
            decimal.Parse(value);
        }
        catch (Exception ex)
        {
            b = false;
        }
        return b;
    }
    protected bool CheckYYYYMM(string s)
    {
        bool b = true;//valid format yyyymm

        if (s.Length > 6 || s.Length < 6)
            b = false;
        else if (!CheckDecimal(s))
            b = false;


        return b;
    }
    protected void btnImport_Click(object sender, EventArgs e)
    {
        string sFullFileName = "", sFileName = "", sFilePath = "", sSheetName = "forecast", sFileExcept = "xls", sSheetRange = "";
        sFullFileName = fileForecast.PostedFile.FileName;

        sSheetName = ConfigurationManager.AppSettings["SheetName"].ToString();
        sFileExcept = ConfigurationManager.AppSettings["FileExcept"].ToString();
        sSheetRange = ConfigurationManager.AppSettings["SheetRange"].ToString();
        //read picture size
        int len = fileForecast.PostedFile.ContentLength;
        //get file name
        sFullFileName = fileForecast.PostedFile.FileName;

        bool b = CheckFileUpload(sFullFileName);
        if (b)
        {
            sFileName = sFullFileName.Substring(sFullFileName.LastIndexOf("\\") + 1);

            sFilePath = Server.MapPath(ConfigurationManager.AppSettings["ExcelPath"].ToString().Trim());
            sFilePath = sFilePath + "\\" + sFileName;
            bool bExist = System.IO.File.Exists(sFilePath);
            if (bExist)
            {
                try
                {
                    System.IO.File.Delete(sFilePath);
                }
                catch (System.IO.IOException ex)
                {
                    //ShowMessage(ex.Message.ToString());
                }
                catch (UnauthorizedAccessException uax)
                {
                    // ShowMessage(uax.Message.ToString());
                }
            }

            try
            {
                fileForecast.PostedFile.SaveAs(sFilePath);
            }
            catch (System.IO.IOException ex)
            {
                //ShowMessage(ex.Message.ToString());
            }
            catch (UnauthorizedAccessException uax)
            {
                //ShowMessage(uax.Message.ToString());
            }
            catch (Exception ex)
            {
                //ShowMessage(ex.Message.ToString());
            }

            /**/
            clsWebShop cls = new clsWebShop();
            CExcel oExc = new CExcel(sFilePath, sSheetName, sSheetRange);
            DataTable dtExcel = new DataTable();
            
           

            try
            {
                DataTable dtSrc=new DataTable();
                
                dtExcel = oExc.Read();
                if (dtExcel.Rows.Count > 0)
                {
                    DataTable dtTT = new DataTable();
                    dtTT = cls.GetData("SELECT  *  FROM Catalogue cat left outer join cat_Properties p on cat.CatID=p.CatID where cat.Status<>'D'").Tables[0];

                    string sTenSP = "",sNoiDung="", sTenTL = "", sMaTL = "", sListErr = "",sDungLuong="", Col_Value_0="",sMaTT="" ;
                    PccMsg msgOut = new PccMsg();
                    DataColumnCollection columns = dtExcel.Columns;
                    if (columns.Contains("Ten SP") && columns.Contains("The Loai"))
                    {
                        try
                        {                           
                            int iCount = 0, iImportRecord = 0;
                            PccMsg msgErrors = new PccMsg();
                            iCount = dtExcel.Rows.Count;
                            TableCell cell;
                            TableRow row;
                            for (int i = 0; i < iCount; i++)
                            {
                                if (dtExcel.Rows[i].RowState != DataRowState.Deleted)
                                {
                                    string Err = "N", strValue="",col_0="" ;
                                    row = new TableRow();
                                    try
                                    {

                                        sTenSP = dtExcel.Rows[i]["Ten SP"].ToString();
                                        sTenTL = dtExcel.Rows[i]["The Loai"].ToString();
                                        sNoiDung = dtExcel.Rows[i]["Noi Dung"].ToString();
                                        sDungLuong = dtExcel.Rows[i]["Dung luong"].ToString().Replace(" ",".");
                                        if (sTenSP != "" && sTenTL != "")
                                        {
                                            try
                                            {
                                                //Lấy Mã Thể loại SQL theo tên thể loại Excel
                                                sMaTL = dtTT.Select("CatName='" + sTenTL + "'")[0]["CatID"].ToString();

                                                
                                                try
                                                {
                                                    string sListTT = "";
                                                     //Ap dung STT tu cot 1

                                                     //*************
                                                     //Lay cot ma so
                                                    col_0 = columns[0].ToString();
                                                    Col_Value_0 = dtExcel.Rows[i][0].ToString();
                                                     //So sanh theo ten the loai cua excel de may ma the loai trong sql
                                                    sMaTT = dtTT.Select("CatName='" + sTenTL + "' and PrtNm='" + col_0 + "'")[0]["PrtID"].ToString();
                                                    if (Col_Value_0.Trim() != "")
                                                    {
                                                        sListTT += Col_Value_0.Trim() + "|" + sMaTT + "^";
                                                    }

                                                    #region "Lay thuoc tinh"
                                                    //Ap dung thuoc tinh tu cot 5 tro di
                                                    for (int j = 5; j < columns.Count; j++)
                                                    {
                                                            col_0 = columns[j].ToString();
                                                            Col_Value_0 = dtExcel.Rows[i][j].ToString();
                                                            sMaTT = dtTT.Select("CatName='" + sTenTL + "' and PrtNm='" + col_0 + "'")[0]["PrtID"].ToString();                                                            
                                                            if (Col_Value_0.Trim() != "")
                                                            {
                                                                sListTT += Col_Value_0.Trim() + "|" + sMaTT + "^";
                                                            }

                                                        }
                                                    #endregion
                                                        if (sListTT != "")
                                                        sListTT = sListTT.Substring(0, sListTT.LastIndexOf("^"));



                                                    PccMsg msg = new PccMsg();
                                                     
                                                    msg.CreateFirstNode("PDID", "0");
                                                    msg.CreateFirstNode("PdName", sTenSP);
                                                    msg.CreateFirstNode("CatID", sMaTL);
                                                    msg.CreateFirstNode("Price", "0");
                                                    msg.CreateFirstNode("Warranty", "");
                                                    msg.CreateFirstNode("Descript", sNoiDung);
                                                    msg.CreateFirstNode("ImgURL", "Images/Products/" + sTenSP + ".jpg");
                                                    msg.CreateFirstNode("Quantity", "0");
                                                    msg.CreateFirstNode("Capacity", sDungLuong);
                                                    msg.CreateFirstNode("Unit", "Film");
                                                    msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
                                                    msg.CreateFirstNode("strProperties", sListTT);

                                                    string sXML = "";
                                                    sXML = cls.ImportPD(msg.GetXmlStr.ToString());
                                                    msg = new PccMsg(sXML);
                                                    strValue = msg.Query("strOutput");
                                                    

                                                    if (strValue != "0")// danh sach loi
                                                    {
                                                        cell = new TableCell();
                                                        sListErr = RptErrString(strValue);
                                                        cell.Text = sListErr;
                                                        row.CssClass = "rowInValid";
                                                        cell.CssClass = "cell_Err";
                                                        row.Cells.Add(cell);

                                                    }
                                                    else
                                                    {
                                                        cell = new TableCell();
                                                        cell.Text = "Thêm thành công";
                                                        iImportRecord++;
                                                        row.CssClass = "rowValid";
                                                        cell.CssClass = "cell_Err";
                                                        row.Cells.Add(cell);
                                                    }
                                                       
                                                      
                                                } 

                                                catch (Exception ex) { Err = "TT"; }
                                            }
                                            catch (Exception ex) {  Err = "TL"; }



                                        }
                                        else
                                        {
                                            string str = "";
                                            if (sTenSP == "")
                                                str += "sản phẩm ";
                                            if (sTenTL == "")
                                                str += "thể loại ";
                                            str += "không hợp lệ";

                                            cell = new TableCell();
                                            cell.Text = str;
                                            cell.CssClass = "cell_Err";
                                            row.Cells.Add(cell);
                                    
                                        }

                                        
                                    }
                                    catch (Exception ex) { }
                                    if (sTenSP != "" && sTenTL != "")
                                    {
                                        if (Err == "TL")
                                        {
                                            cell = new TableCell();
                                            cell.Text = "Thể loại không tồn tại";
                                            cell.CssClass = "cell_Err";
                                            row.Cells.Add(cell);
                                            row.CssClass = "rowInValid";

                                        }
                                        else if (Err == "TT")
                                        {
                                            cell = new TableCell();
                                            cell.Text = "Thuộc tính không tồn tại (" + col_0 + ")";
                                            cell.CssClass = "cell_Err";
                                            row.Cells.Add(cell);
                                            row.CssClass = "rowInValid";
                                        }


                                        cell = new TableCell();
                                        cell.Text = sTenSP;
                                        cell.CssClass = "cell_Valid";
                                        row.Cells.Add(cell);
                                        cell = new TableCell();
                                        cell.Text = sTenTL;
                                        cell.CssClass = "cell_Valid";
                                        row.Cells.Add(cell);
                                        tblOutput.Rows.Add(row);
                                    }
                                }
                            }//end for i

                                      


                            lblTotal.Text = "Tổng số dòng được thêm vào : " + iImportRecord.ToString();

                        }
                        catch (Exception ex)
                        {
                            ShowMessage(ex.Message.ToString());
                        }


                    }
                    else
                    {
                        //Ten cot phai la"Art code","Model","Total"z
                        ShowMessage("Ten cot phai co ten la 'Ten SP', 'The Loai'");
                    }
                
                }
            }
            catch (System.Data.OleDb.OleDbException ex)
            {
                ShowMessage(ex.Message.ToString());
            }

        }
        else
        {
            ShowMessage("Chon file Excel");
        }
    
    }

    private string RptErrString(string err)
    {
        //Thanh cong:0
        //Bi loi:-1 SP,-2 Thuoc tinh,-3 Trung File
        string strReturn="";
        switch (err)
        {
            case "I":
                strReturn = "Lỗi thêm sản phẩm";
                break;
            case "P":
                strReturn = "Lỗi thêm thuộc tính";
                break;
            case "S":
                strReturn = "Lỗi trùng tên";
                break;
        }
        return strReturn;
    }

    private void ShowMessage(string sMsg)
    {
        sMsg = sMsg.Replace("'", " ");
        sMsg = sMsg.Replace("\n", " ");
        Response.Write("<script>alert('" + sMsg + "')</script>");
    }


}
